package ttestClosed;

import java.io.IOException;
import java.util.Arrays;
import java.util.concurrent.ScheduledThreadPoolExecutor;

@SuppressWarnings("all")
public class TestChannelSingleton {

    // TODO Should be a independent process

    private static final int FRAMESIZE = 20;

    private ScheduledThreadPoolExecutor schExecuter;
    private static TestChannelSingleton frameInstance = null;
    private boolean[] frame;
    private String mcastAddr;
    private int mcastPort;
    private String ifaceAddr;
    private int udpPort;

    private TestChannelSingleton(String mcastAddr, int mcastPort,
            String ifaceAddr, int udpPort) {
        super();
        this.schExecuter = new ScheduledThreadPoolExecutor(20);
        this.frame = new boolean[FRAMESIZE];
        Arrays.fill(frame, Boolean.TRUE);
        this.mcastAddr = mcastAddr;
        this.mcastPort = mcastPort;
        this.ifaceAddr = ifaceAddr;
        this.udpPort = udpPort;
    }

    public boolean[] getFrame() {
        return frame;
    }

    public static TestChannelSingleton getFrameInstance(String mcastAddr,
            int mcastPort, String ifaceAddr, int udpPort) {
        if (frameInstance == null) {
            synchronized (TestChannelSingleton.class) {
                if (frameInstance == null) {
                    // --
                    frameInstance = new TestChannelSingleton(mcastAddr,
                            mcastPort, ifaceAddr, udpPort);
                }
            }
        }
        return frameInstance;
    }

    public static void initFrameInstance(String mcastAddr, int mcastPort,
            String ifaceAddr, int udpPort) {
        // TODO write initialize method for singleton
    }

    public void scheduleSlot(long delay) throws IOException {
//        schExecuter.schedule(new Sender(this.ifaceAddr, this.udpPort,
//                this.mcastAddr, this.mcastPort), delay, TimeUnit.MILLISECONDS);
    }

    public byte searchSlot() {
        byte freeSlot = -1;
        byte i = 0;
        for (; frame[i] != true && i < frame.length; i++) {
            freeSlot = i;
        }
        return freeSlot;
    }

    public int lockSlot(int position, boolean value) {
        if (position <= FRAMESIZE && position > 0) {
            frame[position] = value;
            return 1;
        } else {
            return -1;
        }
    }

}
